<?php
/**
 * tree $id 01 - 10/10/2009
 *
 * Class to manage the Doctrine_Tree
 *
 * JLoja Project
 * @package    jloja.db.tree
 * @author     Joao Neto <joao_neto@ymail.com>
 * @version    0.1
 */

class JLoja_Db_Tree
{
	/**
	 * A Tree Object
	 * @var Doctrine_Tree_NestedSet
	 */
	private $_tree = null;

	public function __construct( Doctrine_Tree_NestedSet $treeObject )
	{
		$this->_tree = $treeObject;
	}

	/**
	 * Fetch a Tree with all roots and childs
	 * @param Doctrine_Query $q base query
	 * @return mixed Depending of Hydrate Mode
	 */
	public function fetchTree( $q = null, $hydrationMode = null )
	{
		$q->addOrderBy( $this->_tree->getBaseAlias() . "." .  $this->_tree->getAttribute('rootColumnName') );
		$q->addOrderBy( $this->_tree->getBaseAlias() . ".lft ASC" );
		$q->addOrderBy( $this->_tree->getBaseAlias() . ".level ASC" );
		
		if( $q ){
			$this->_tree->setBaseQuery( $q );
		}

		// fetch tree
		$q = $this->_tree->getBaseQuery();

		$depth = isset($options['depth']) ? $options['depth'] : null;

		$q->addWhere($this->_tree->getBaseAlias() . ".lft >= ?", 1);

		if ( ! is_null($depth)) {
			$q->addWhere($this->_tree->getBaseAlias() . ".level BETWEEN ? AND ?", array(0, $depth));
		}

		$tree = $q->execute(array(), $hydrationMode);

		if (count($tree) <= 0) {
			return false;
		}

		return $tree;
	}
	/**
	 * Return a tree Object
	 * @return Doctrine_Tree_NestedSet
	 */
	public function getTree()
	{
		return $this->_tree;
	}

	/**
	 * Set a TreeObject
	 * @param Doctrine_Tree_NestedSet $_tree
	 */
	public function setTree( Doctrine_Tree_NestedSet $_tree)
	{
		$this->_tree = $_tree;
		return $this;
	}


}